<template>
  <div class="goods-add">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-page-header @back="goBack">
            <template #content>修改商品</template>
          </el-page-header>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="goods-form">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="form.price"
            :min="0"
            :precision="2"
            :step="0.1"
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="商品分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option label="手机数码" value="1" />
            <el-option label="家用电器" value="2" />
            <el-option label="电脑办公" value="3" />
            <el-option label="服装配饰" value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品图片" prop="image">
          <el-upload
            class="goods-uploader"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="customUpload">
            <img v-if="form.image" :src="form.image" class="goods-image" />
            <el-icon v-else class="goods-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">
            只能上传 jpg/png 文件，且不超过 2MB
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="subloading">
            提交
          </el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter , useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const loading = ref(false)
const subloading = ref(false)

const form = reactive({
  name: '',
  category: '',
  price: 0,
  image: '',
  description: '',
})

const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传商品图片', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' }
  ]
}

//获取商品
const getGoodsDetail = async () => {
    loading.value = true
    try{
        const res = await request({
            url:`/goods/${route.params.id}`,
            method: 'get'
        })
        Object.assign(form, res.data)
    }catch(error){
        console.error('获取商品详情失败:',error);
    }finally{
        loading.value = false
    }
}

// 上传图片前的验证
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传方法
const customUpload = async (options) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    const res = await request({
      url: '/upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    form.image = res.data.url
    ElMessage.success('上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      subloading.value = true
      try {
        await request({
          url: '/goods',
          method: 'post',
          data: form
        })
        ElMessage.success('修改成功')
        goBack()
      } catch (error) {
        console.error('添加商品失败:', error)
      } finally {
        subloading.value = false
      }
    }
  })
}

const goBack = () => {
  router.back()
}

onMounted(() => {
    getGoodsDetail()
})
</script>

<style scoped>
  .card-header {
    padding: 10px 0;
  }

  .goods-form {
    max-width: 800px;
    margin: 0 auto;
    padding-top: 20px;
  }

  .goods-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
  }

  .goods-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
  }

  .goods-image {
    width: 178px;
    height: 178px;
    display: block;
  }

</style> 